package model.user;

import core.Database;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import model.beans.LinkBean;
import model.beans.OrderBean;
import model.beans.RouterBean;
import org.apache.log4j.Logger;

/**
 *
 * @author Danon
 */
@ManagedBean
@SessionScoped
public class OrderDetailsBean {

    private static final Logger logger = Logger.getLogger(OrderDetailsBean.class);
    
    private OrderBean order;
    
    /** Creates a new instance of OrderDetailsBean */
    public OrderDetailsBean() {
    }
    
    public OrderBean getOrder() {
        return order;
    }

    public List<LinkBean> getPath() {
        List<LinkBean> lst = new ArrayList<>();
        if(order == null)
            return lst;
        try {
            Connection c = Database.getInstance().getConnection();
            try (PreparedStatement ps = c.prepareStatement("select e.num, l.link_id, l.title, l.src_router, l.dst_router, l.bandwidth "
                    + "from links l, engagements e "
                    + "where e.order_id = ? and e.link_id = l.link_id "
                    + "order by 1 desc")) {
                ps.setInt(1, order.getId());
                ResultSet rs = ps.executeQuery();
                while(rs.next()) {
                   LinkBean l = new LinkBean(rs.getInt("link_id"), rs.getString("title"), rs.getFloat("bandwidth"));
                   l.setRouter1(RouterBean.loadById(rs.getInt("src_router")));
                   l.setRouter2(RouterBean.loadById(rs.getInt("dst_router")));
                   lst.add(l);
                }
                rs.close();
            }
        } catch (Exception ex) { 
            logger.debug(ex.getMessage()); 
        }
        return lst;
    }
    
    public String show(OrderBean order) {
        this.order = order;
        return "order-details?faces-redirect=true";
    }
}
